package com.whq.thrift.api.web.admin.service.job;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.whq.common.DateUtil;
import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.common.spring.ReloadableConfManager;
import com.whq.thrift.api.web.admin.db.requestlog.RequestLog;
import com.whq.thrift.api.web.admin.service.requestlog.RequestLogService;
/**
 * 按天统计requestlog数据
 * @author v.qiuzhipin
 *
 */
@Service
public class StatRequestDateApiDataJob {
	private static final Logger LOGGER = LoggerFactory.getLogger(MonitorConsumeLogInfoJob.class);
	private static final Logger LOGGER_QUARTZ = LoggerFactory.getLogger(CommonConfigConstants.LOGGER_KEY_QUARTZ);

	@Autowired
	private RequestLogService requestLogService;

	@Autowired
	private ReloadableConfManager reloadableConfManager;

	public void statRequestDateApiData() {
		LOGGER_QUARTZ.info("begin stat requestlog date info data");

		int thresholdDay = reloadableConfManager.getIntPropertyValue("stat.delete.day.threshold", null, 20);
		// 获取当前时间日期
		long currentTimeMillis = System.currentTimeMillis();
		Date currentTime = new Date(currentTimeMillis);
		Date startDate = DateUtil.getOffsetDateBegin(currentTime, -1);
		Date endDate = DateUtil.getOffsetDateBegin(currentTime, 0);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String statDay = sdf.format(startDate);

		// 获取要删除的表数据的时间条件,删除20天之前的数据
		try {
			Date thresholdDate = DateUtil.getOffsetDateBegin(startDate, -thresholdDay);
			String thresholdTime = format.format(thresholdDate);
			this.requestLogService.delDataApiData(thresholdTime);
		} catch (Exception e) {
			LOGGER.error("delete date requestLog exception" ,e);
		}

		// 获取启动时间
		String startTime = format.format(startDate);

		// 获取结束时间
		String endTime = format.format(endDate);

		// 获取当前requestLog的具体数据表
		RequestLog requestLog = new RequestLog();
		requestLog.setTime(startDate);
		int tableSeq = requestLog.getTableSeq();

		try {
			this.requestLogService.replaceStatDateApiData(tableSeq, statDay, startTime, endTime);
		} catch (Exception e) {
			LOGGER.error("replace date requestLog exception" , e);
		}

		long duMillis = System.currentTimeMillis() - currentTimeMillis;

		LOGGER_QUARTZ.info("end stat date requestlog data [" + (duMillis / 1000) + "s]");
	}
}
